package com.weixin.project.Controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.weixin.project.Annotation.AdminAccess;
import com.weixin.project.Common.Enum.UserType;
import com.weixin.project.Config.Config;
import com.weixin.project.Entity.*;
import com.weixin.project.Service.QuestionService;
import com.weixin.project.Service.UserService;
import com.weixin.project.Util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.List;

@RestController
public class QuestionController {
    @Autowired
    QuestionService questionService;
    @Autowired
    UserService userService;
    @Value("${logging.pattern.dateformat}")
    String dateFormat;
    @Value("${document.jsonPath}")
    String uploadPath;

    @GetMapping("/chapter/get_question_bank")
    JSONObject getAllQuestionBanks(){
        JSONObject ret = new JSONObject();
        List<QuestionBank> questionBanks = questionService.findAllQuestionBanks();
        JSONArray jsonArray = new JSONArray();
        for(QuestionBank questionBank:questionBanks){
            JSONObject obj = new JSONObject();
            obj.put("bank_id", questionBank.getId());
            obj.put("bank_name", questionBank.getBankName());
            obj.put("bank_cover", questionBank.getCover());
            obj.put("question_number", questionService.countQuestionsOfBank(questionBank.getId()));
            jsonArray.add(obj);
        }
        ret.put("question_bank", jsonArray);
        return ret;
    }

    @GetMapping("/chapter/list")
    JSONObject getChapterList(@RequestParam("id") Integer questionBankId){
        JSONObject ret = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        List<Chapter> chapters = questionService.findChapters(questionBankId);
        for(Chapter chapter:chapters){
            JSONObject obj = new JSONObject();
            obj.put("chapter_name", chapter.getChapterName());
            obj.put("chapter_id", chapter.getId());
            jsonArray.add(obj);
        }
        ret.put("chapter", jsonArray);
        return ret;
    }

    @GetMapping("/test/answer")
    JSONObject getAnswers(@RequestParam("id") Integer questionId){
        JSONObject ret = new JSONObject();
        List<Answer> answers = questionService.findAnswers(questionId);
        JSONArray jsonArray = new JSONArray();
        for(Answer answer:answers){
            JSONObject obj = new JSONObject();
            obj.put("answer", answer.getContent());
            obj.put("is_right", answer.isRightAnswer());
            jsonArray.add(obj);
        }
        ret.put("answers", jsonArray);
        return ResponseUtil.success("",ret);
    }

    @GetMapping("/test/text")
    JSONObject getQuestionText(HttpServletRequest request,
                               @RequestParam("chapter_id") Integer chapterId,
                               @RequestParam("page") Integer page) {
        User currentUser = userService.findCurrentUser(request);
        Chapter chapter = questionService.findChapter(chapterId);
        if (Config.IS_CHARGE && !chapter.getFree() && !currentUser.getType().equals(UserType.VIP)){
            return ResponseUtil.requireVIP();
        }
        JSONObject ret = new JSONObject();
        page -= 1;
        Question question = questionService.findQuestionByChapterId(chapterId, page);
        if (question == null) {
            return ResponseUtil.error("Oops, question of this Page is missing");
        }
        JSONObject problem = new JSONObject();
        problem.put("stem", question.getStem());
        problem.put("explain", question.getExplanation());
        problem.put("score", question.getScore());
        problem.put("difficulty", question.getDifficulty());
        problem.put("type_id", question.getTypeId());
        problem.put("id", question.getId());
        ret.put("problem",problem);
        return ResponseUtil.success("", ret);
    }

    @GetMapping("/test/chapter_problem_count")
    JSONObject getCountOfChapterProblems(@RequestParam("chapter_id") Integer chapterId){
        JSONObject ret = new JSONObject();
        ret.put("chapter_problem_count", questionService.countQuestionsOfChapter(chapterId));
        return ResponseUtil.success("", ret);
    }

    @GetMapping("/test/text_by_id")
    JSONObject getQuestionById(@RequestParam("id") Integer id){
        Question question = questionService.findQuestionById(id);
        JSONObject ret = new JSONObject();
        ret.put("stem", question.getStem());
        ret.put("explain", question.getExplanation());
        ret.put("score", question.getScore());
        ret.put("difficulty", question.getDifficulty());
        ret.put("position", 0);
        ret.put("type_id", question.getTypeId());
        ret.put("id", question.getId());
        return ResponseUtil.success("", ret);
    }

//    @AdminAccess
//    @PostMapping("/question/upload/json")
//    JSONObject uploadQuestionInJSON(@RequestBody JSONObject params){
//        QuestionUploadRecord record = questionService.previewQuestionUploadResults(params.getString("path"), params.getString("json_str"));
//        JSONObject ret = new JSONObject();
//        ret.put("path", record.getJsonPath());
//        ret.put("preview", record.getPreview());
//        ret.put("upload_id", record.getId());
//        return ResponseUtil.success(ret);
//    }

    //本地运行调时候调用这个，云托管部署用上面那个
    @AdminAccess
    @PostMapping("/question/upload/json")
    JSONObject uploadQuestionInJSON(@RequestParam("file") MultipartFile file){
        try {
            QuestionUploadRecord record = questionService.previewQuestionUploadResults(file);
            JSONObject ret = new JSONObject();
            ret.put("path", record.getJsonPath());
            ret.put("preview", record.getPreview());
            ret.put("upload_id", record.getId());
            return ResponseUtil.success(ret);
        } catch (Exception e){
            e.printStackTrace();
            return ResponseUtil.error("File upload failed!");
        }
    }

    @AdminAccess
    @PostMapping("/question/upload/confirm")
    JSONObject confirmQuestionUpload(@RequestBody JSONObject params){
        questionService.confirmUpload(params.getInteger("id"), params.getBoolean("confirm"));
        return ResponseUtil.success();
    }

    @AdminAccess
    @GetMapping("/question/upload/histories")
    JSONObject viewUploadHistories(){
        List<QuestionUploadRecord> records = questionService.viewQuestionUploadRecords();
        JSONArray array = new JSONArray();
        for (QuestionUploadRecord record:records){
            JSONObject obj = new JSONObject();
            obj.put("create_time", new SimpleDateFormat(dateFormat).format(record.getCreateTime()));
            obj.put("id", record.getId());
            obj.put("json_file", record.getJsonPath());
            obj.put("bank_name", record.getBankName());
            array.add(obj);
        }
        JSONObject ret = new JSONObject();
        ret.put("records", array);
        return ResponseUtil.success(ret);
    }

    @AdminAccess
    @PostMapping("/question/upload/rollback")
    JSONObject rollBack(@RequestBody JSONObject params){
        questionService.rollbackUpload(params.getInteger("id"));
        return ResponseUtil.success();
    }
}
